<?php
namespace WXAPI\Controller;
use Think\Controller;
use WXAPI\Logic\UsersLogic;
use Think\Page;
class UserController extends BaseController {
    public $userLogic;
    public $huilv=0.01;
    protected $logistics_state_array = [
        [
            'id' => 1,
            'name'  => '打包'
        ],
        [
            'id' => 2,
            'name'  => '出库'
        ],
        [
            'id' => 3,
            'name'  => '配送'
        ],
        [
            'id' => 4,
            'name'  => '付款'
        ],
        [
            'id' => 5,
            'name'  => '完成'
        ]
    ];
    /**
     * 析构流函数
     */
    public function  __construct(){
        parent::__construct();
		$this->huilv=1/tpCache('shopping')['point_rate'];
    }
    
    public function _initialize(){
        parent::_initialize();
        $this->userLogic = new UsersLogic();
    }
    /**
     * 用户投诉
     * */
    public function saveTousu(){
        $user_id = I('user_id');
        $pingfen = I('pingfen');
        $beizhu = I('beizhu');
        if(!$user_id)
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        //限制一天一条投诉
        $today = strtotime(date('Y-m-d',time()));
        $endToday = $today+86399;
        $complaintCount = M('tousu')->where('add_time >'.$today.' and add_time<'.$endToday)->where(['user_id'=>$user_id])->count();
        if($complaintCount >= 1){
            exit(json_encode(array('status'=>-1,'msg'=>'一天只能投诉一条','result'=>'')));
        }

        $data = [];
        $data['user_id'] = $user_id;
        $data['pingfen'] = $pingfen;
        $data['content'] = $beizhu;
        $data['add_time'] = time();
        $data['duixiang'] = '用户';
        $data = M('tousu')->add($data);
        if(!empty($data)){
            exit(json_encode(array('status'=>1,'msg'=>'投诉成功','result'=>'')));
        }else{
            exit(json_encode(array('status'=>0,'msg'=>'投诉失败','result'=>'')));
        }

    }

    /**
     * 获取所有业务员
     * */
    public function salesmanlist(){
        $page = I('page',0);
        $limit = I('limit',20);
        $showPage = $page*$limit;
        $where = [];
        if(!empty(I('mobile'))){
            $where = 'mobile like "%'.I('mobile').'%" or company like "%'.I('mobile').'%" or nickname like "%'.I('mobile').'%"';
        }

        $data =  M('users')->where(array("salesman"=>1))
            ->limit($showPage,$limit)
            ->where($where)
            ->select();
        $json_arr = array('status'=>1,'msg'=>'成功!','result'=>$data);
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    /**
     * 获取全部地址信息
     */
    public function getArea(){
        $data =  M('region')->where(array("parent_id"=>$_GET['parent_id']))->select();
        $json_arr = array('status'=>1,'msg'=>'成功!','result'=>$data);
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    /**
     *  登录
     */
    public function login(){
        $username = I('username','');
        $password = I('password','');
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        $data = $this->userLogic->app_login($username,encrypt($password));

        if($data['status'] != 1)
            exit(json_encode($data));

//        $cartLogic = new \Home\Logic\CartLogic();
//        $cartLogic->login_cart_handle($unique_id,$data['result']['user_id']); // 用户登录后 需要对购物车 一些操作
        exit(json_encode($data));
    }
    /*
     * 第三方登录
     */
    public function thirdLogin(){
        $map['openid'] = I('openid','');
        $map['oauth'] = I('from','');
        $map['nickname'] = I('nickname','');
        $map['head_pic'] = I('head_pic','');        
        $data = $this->userLogic->thirdLogin($map);
        exit(json_encode($data));
    }

    /**
     * 用户注册
     */
    public function reg(){
        $username = I('post.username','');
        $password = I('post.password','');
        $password2 = I('post.password2','');
        $unique_id = I('unique_id');
        //是否开启注册验证码机制
        if(check_mobile($username) && TpCache('sms.regis_sms_enable')){
            $code = I('post.code');
            if(empty($code))
                exit(json_encode(array('status'=>-1,'msg'=>'请输入验证码','result'=>'')));                
            $check_code = $this->userLogic->sms_code_verify($username,$code,$unique_id);
            if($check_code['status'] != 1)
                exit(json_encode(array('status'=>-1,'msg'=>$check_code['msg'],'result'=>'')));
        }        
        $data = $this->userLogic->reg($username,$password,$password2);
        exit(json_encode($data));
    }

    /*
     * 搜索代金券 维亚轩 青 2019-4-17 11:02:51
     */
    public function duihuanma(){
        
        $user_id = I('user_id');
        $duihuanma = I('duihuan');
        if ($user_id > 0 && $duihuanma) {
            $where['code'] = $duihuanma;
            $where['uid'] = 0;
            $coupon = M("coupon_list")->where($where)->find();
            if ($coupon['id'] > 0) {
                $cou_where['id'] = $coupon['cid'];
                $cou = M("coupon")->where($cou_where)->find();
                if ($cou['id'] > 0 && time() > $cou['send_start_time'] && time() < $cou['send_end_time']) {
                    $store_name = M("store")->where(array('store_id'=>$cou['store_id']))->getField('store_name');
                    $result['id'] = $cou['id'];
                    $result['condition'] = $cou['condition'];
                    $result['money'] = $cou['money'];
                    $result['name'] = $cou['name'];
                    $result['send_end_time'] = date("Y-m-d",$cou['send_end_time']);
                    $result['send_num'] = $cou['send_num'];
                    $result['send_start_time'] = date("Y-m-d",$cou['send_start_time']);
                    $result['type'] = $cou['type'];
                    $result['use_end_time'] = date("Y-m-d",$cou['use_end_time']);
                    $result['use_start_time'] = date("Y-m-d",$cou['use_start_time']);
                    $result['list_id'] = $coupon['id'];
                    $result['c_status'] = 2;
                    $result['code'] = $coupon['code'];
                    $result['store_name'] = $store_name;

                    $data['status'] = 1;
                    $data['msg'] = '搜索成功';
                    $data['result'] = $result;
                }else{
                    $data['status'] = -1;
                    $data['msg'] = '未找到代金券';
                    $data['result'] = '';
                }
            }else{
                $data['status'] = -1;
                $data['msg'] = '未找到代金券';
                $data['result'] = '';
            }
// echo "<pre>";print_r($coupon);exit;
        }else{
            $data['status'] = -1;
            $data['msg'] = '搜索失败';
            $data['result'] = '';
        }
        exit(json_encode($data));
    }

    /*
     * 获取用户信息
     */
    public function userInfo(){
        //$user_id = I('user_id');
        $data = $this->userLogic->get_info($this->user_id);
        exit(json_encode($data));
    }

    /*
     * 获取用户会员中心的资料 //edit sofwu
     */
    public function getusercenter(){
        $user_id = I('user_id');
        if($user_id){
            $users = M('users')->where(array("user_id"=>$user_id))->find();
            $user_id = $users['user_id'];
            if($users['is_lock']==1)
                exit;

        }

        $data = $this->userLogic->get_info($user_id);

        //判断客户是否有店铺，有店铺显示我的商家中心
        $is_store =  M('store')->where(array('user_id'=>$user_id))->select();
        if($is_store){
            $data['result']['is_store']=1;
        }else{

            $data['result']['is_store']=0;
        }
        $huilv=$this->huilv;
        $data['result']['pay_point_price']=$data['result']['pay_points'];
        $data['result']['huilv']=$huilv;
        // $data['result']['pay_points']=geshi($data['result']['pay_points']*$huilv);
        $data['result']['pay_points']=0;
        $data['result']['pay_online']=tpCache("basic")['is_pays'];
        $data['result']['bg_images']=SITE_URL."/Public/bootstrap/img/bg.jpg";
        if(empty($data['result']['mobile'])){

            $data['result']['is_phone']=1;
        }else{

            $data['result']['is_phone']=0;
        }
        exit(json_encode($data));
    }
//
//    /*
//     *更新用户信息
//     */
//    public function updateUserInfo(){
//        if(IS_POST){
//            //$user_id = I('user_id');
//            if(!$this->user_id)
//                exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
//
//            I('post.nickname') ? $post['nickname'] = I('post.nickname') : false; //昵称
//            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
//            I('post.head_pic') ? $post['head_pic'] = I('post.head_pic') : false; //头像地址
//            I('post.sex') ? $post['sex'] = I('post.sex') : false;  // 性别
//            I('post.birthday') ? $post['birthday'] = strtotime(I('post.birthday')) : false;  // 生日
//            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
//            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
//            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
//
//            if(!$this->userLogic->update_info($this->user_id,$post))
//                exit(json_encode(array('status'=>-1,'msg'=>'更新失败','result'=>'')));
//            exit(json_encode(array('status'=>1,'msg'=>'更新成功','result'=>'')));
//
//        }
//    }


    /*
   *更新用户信息新 by sofwu
   */
    public function updateUserInfo(){

        //$user_id = I('user_id');
        if(!$this->user_id)
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));

        I('nick_name') ? $get['nick_name'] = I('nick_name') : false; //昵称
        I('head_pic') ? $get['head_pic'] = I('head_pic') : false; //头像地址
        I('company_address') ? $get['company_address'] = I('company_address') : false; //头像地址
        I('environmentalphotos') ? $get['environmentalphotos'] = I('environmentalphotos') : false; //头像地址
        I('doorphoto') ? $get['doorphoto'] = I('doorphoto') : false; //头像地址
        I('open_id') ? $get['open_id'] = I('open_id') : false; //头像地址
     
        if(!M('users')->where("user_id = ".$this->user_id)->save($get))
            exit(json_encode(array('status'=>-1,'msg'=>'更新失败','result'=>'')));
        exit(json_encode(array('status'=>1,'msg'=>'更新成功','result'=>'')));

    }

    /**
     * 上传头像 by sofwu
     */
    public function upload_avatar()
    {
        //得到传输的数据
        $file = $_FILES['image'];

        //得到文件名称
        $name = $file['name'];

        $type = 'png';

        //判断是否是通过HTTP POST上传的
        if(!is_uploaded_file($file['tmp_name'])){
            //如果不是通过HTTP POST上传的
            return ;
        }
        $upload_path = "./Public/upload/avatar/"; //上传文件的存放路径
        if (!file_exists($upload_path)){
            mkdir ($upload_path,0777,true);//不存在 创建新文件夹
        }
        $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
        $rand = substr($randStr,0,6);
        $name = date('YmdHis').$rand.".".$type;
        //开始移动文件到相应的文件夹
        if(move_uploaded_file($file['tmp_name'],$upload_path.$name)){
            $path = substr($upload_path.$name,1);
            $data = json_encode(array("code"=>0,"url"=>SITE_URL.$path));
            echo $data;
        }else{
            echo "Failed!";
        }


    }

    /**
     * 获取签到的积分数，以及该用户的积分
     */
    public function getPoints()
    {
       $user_id =  I('user_id','');
        $points= M('users')->where(array('user_id'=>$user_id))->getField('pay_points');
        $sign_in = M('sign_in')->field('sign_points,sign,score')->select();
        $sign_in[0]['sign']=json_decode( $sign_in[0]['sign']);
        $sign_in[0]['score']=json_decode($sign_in[0]['score']);
        $data['signs']=array_combine($sign_in[0]['sign'],$sign_in[0]['score']);

        $time = date('Y-n');

        $sign_count=M('sign_point')->field('sign_date')->where("user_id ={$user_id} and sign_date like '%{$time}%'")->order('sign_date desc')->select();

        if ($sign_count){
            foreach ($sign_count as $k=>$v){
                $signdate[]=$v['sign_date'];
            }
            $count = 1;
            for($i=1; $i<count($signdate); $i++){
                $lastone = strtotime($signdate[$i-1]);
                $thisone = strtotime($signdate[$i]);

                if($lastone -  $thisone != 86400){
                    break;
                }
                $count = $count +1;
            }
        }else{
            $count = 0;
        }
       $date = date('Y-n-j');
       $res = M('sign_point')->where("user_id ={$user_id} and sign_date ='$date'")->select();
      if($res){
          $data['is_sign']=1;
      }

        $data['user_points']=$points;
        $data['sign_points']=$sign_in[0]['sign_points'];
        $data['sign_count']=$count;
        $data['signdate']=$signdate;
        if(!$sign_in)
            exit(json_encode(array('status'=>0,'msg'=>'没有数据','result'=>'')));
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$data)));

    }

    /**
     * 保存用户签到的积分
     */
    public function savePoints()
    {
        $data['user_id'] =  I('user_id','');
        $data['sign_points'] =  I('sign_points','');
        $data['sign_date'] = date('Y-n-j');

        $res = M('sign_point')->add($data);
        if($res){

            $sql = "UPDATE __PREFIX__users SET  pay_points = pay_points +  {$data['sign_points']}  WHERE user_id =". $data['user_id'];
            if(! D('users')->execute($sql)){
                exit(json_encode(array('status'=>0,'msg'=>'签到失败!')));
            }
            $time = date('Y-n');
            $sign_count=M('sign_point')->field('sign_date')->where("user_id ={$data['user_id']} and sign_date like '%{$time}%'")->order('sign_date desc')->select();
            if ($sign_count){
                foreach ($sign_count as $k=>$v){
                    $signdate[]=$v['sign_date'];
                }
                $count = 1;
                for($i=1; $i<count($signdate); $i++){
                    if ($signdate[$i-1])
                    $lastone = strtotime($signdate[$i-1]);
                    $thisone = strtotime($signdate[$i]);

                    if($lastone -  $thisone != 86400){
                        break;
                    }
                    $count = $count +1;
                }
            }else{
                $count = 0;
            }
            $points= M('users')->where(array('user_id'=> $data['user_id']))->getField('pay_points');

            exit(json_encode(array('status'=>1,'msg'=>'签到成功','sign_count'=>$count,'today_sign'=> $data['sign_date'],'user_points'=>$points)));
        }
        exit(json_encode(array('status'=>0,'msg'=>'签到失败')));

    }

    /*
         * 修改用户密码
         */
    public function password(){
        $user_id = I('user_id');
        if(!$user_id)
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $data = $this->userLogic->password($this->user_id,I('new_password'),I('confirm_password')); // 获取用户信息
        exit(json_encode($data));
    }

    /**
     * 获取收货地址
     */
    public function getAddressList(){
    	/*"province": "338",
            "city": "569",
            "district": "586",*/
        $this->user_id = I('user_id');
        if(!$this->user_id)
            exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
       $address = M('user_address')->where(array('user_id'=>$this->user_id))->select();
       foreach ($address as $key=>$value)
       {
       	$address[$key]['address'] = M('region')->where(array("id"=>$value['province']))->getField('name').M('region')->where(array("id"=>$value['city']))->getField('name').M('region')->where(array("id"=>$value['district']))->getField('name').$address[$key]['address'];
       }
        if(!$address){
            exit(json_encode(array('status'=>0,'msg'=>'没有数据','result'=>'')));
		}
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$address)));
    }

    /*
     * 添加地址
     */
    public function addAddress(){

    	$object = file_get_contents('php://input');
    	$_POST = (json_decode($object, true));
    	
        $this->user_id = $_POST['user_id'];
        //echo $this->user_id.'1';
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $address_id = I('address_id',0);
        $data = $this->userLogic->add_address($this->user_id,$address_id,I('post.')); // 获取用户信息
        exit(json_encode($data));
    }
    
    /*
     * 获取微信收货地址对应ID BY 维亚轩 Mrlu 2018-04-17
     */
    public function getWxaddressId(){
    	$provinceName = I('provinceName');
		$cityName = I('cityName');
		$countyName = I('countyName');
		
		$provinceId = M('region')->where("name='$provinceName'")->getField('id');
		$cityId = M('region')->where("name='$cityName'")->getField('id');
		$countyId = M('region')->where("name='$countyName'")->getField('id');

        //修复微信获取地址和数据库中的地址名称不符的问题 维亚轩 青 2019-5-9 10:24:00
        if (empty($countyId)) {
            $num = strlen($countyName)/3;//汉字是3个字节
            for ($i=0; $i < $num; $i++) { 
                $a = "-".$i * 3;//汉字是3个字节，每次截取的时候，要乘以3，否则乱码内容导致查询语句出错
                $countyNames = mb_substr($countyName, 0,$a);
                if ($countyNames) {
                    $countyId = M('region')->where("name like '%$countyNames%' AND parent_id = '$cityId'")->getField('id');
                    if ($countyId) {
                        break;
                    }
                }
            }
        }

		$Ids['provinceId'] = $provinceId;
		$Ids['cityId'] = $cityId;
		$Ids['countyId'] = $countyId;
		
        exit(json_encode($Ids));
    }

    /*
     * 总收入 青 2017-8-10 09:32:35
     */
    public function all_amount(){
        $user_id = $_GET['user_id'];
        //echo $this->user_id.'1';
        $all_amount = M('account_log')->where('user_id = '.$user_id)->sum('user_money');
        exit(json_encode($all_amount));
    }

    /*
     * 收入记录 青 2017-8-10 09:32:35
     */
    public function my_bill(){
        $user_id = $_GET['user_id'];
        //echo $this->user_id.'1';
		 $map['user_money']  = array('gt',0);
		 $map['user_id']=$user_id;
        $amount_list = M('account_log')->field('user_money,change_time')->where($map)->select();

        foreach ($amount_list as $k => $v) {
            if (intval($v['user_money']) >= intval(0)) {
                $amount_list[$k]['user_money'] = "+".$v['user_money'];
            }
            $amount_list[$k]['change_time'] = date("Y-m-d",$v['change_time']);
        }
        exit(json_encode($amount_list));
    }

    /*
     * 团队人数 青 2017-8-10 09:32:35
     */
    public function team_number_num(){

        $user_id = $_GET['user_id'];
        $level = I('get.level',1);         
        $condition = array(1=>'first_leader',2=>'second_leader',3=>'third_leader');
        $where = "{$condition[$level]} = {$user_id}";
		$amount = M('users')->where($where)->count();
	    $lists = M('users')->field('nick_name,user_id,distribut_money,reg_time,head_pic')->where($where)->order('user_id desc')->select();
		foreach($lists  as $key=>$value){
			$lists[$key]['head_pic'] = SITE_URL.$value['head_pic'];
			$buy_user_id=$value['user_id'];
			$lists [$key]['distribut_money']=M('rebate_log')->where("buy_user_id=".$buy_user_id)->Sum('money');
			if(empty($lists [$key]['distribut_money'])){
				$lists [$key]['distribut_money']=0;
			}
		}
		//团队总收益
		$get_all_money=M('rebate_log')->where("user_id=".$user_id)->Sum('money');
		if(empty($get_all_money)){
			$get_all_money=0;
		}
		exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('user_num'=>$amount,'user_list'=>$lists,'all_money'=>$get_all_money))));
    }  
	public function updateparent(){
		
        $open_id = $_GET['openid'];
        $user_id = M('users')->where(array("open_id"=>$open_id))->getField("user_id");
		$parent_id = $_GET['parent_id'];
		//查询一下客户是否有下级
		 $map['first_leader']  = array('eq',0);
		 $map['user_id']=$user_id;
		$is_have = M('users')->where($map)->find();
		$sql=M('users')->getLastSql();
		if($user_id != $parent_id){
			if($is_have){
				
				if($parent_id)
				{
					$where_first['user_id']=$parent_id;
					
					$first_leader_info = M('users')->where($where_first)->find();
					if($first_leader_info['is_distribut']>0){
						$date['first_leader'] = $parent_id; // 推荐人id
						$date['second_leader'] = $first_leader_info['first_leader'];
						$date['third_leader'] = $first_leader_info['second_leader'];
					}else{
						
						exit(json_encode(array('status'=>0,'msg'=>'推荐人不是分销商')));
					}
				}else{
			
					exit(json_encode(array('status'=>0,'msg'=>'推荐ID为0')));
			
				}		
				$where['user_id']=$user_id;
				M('users')->where($where)->save($date);
			}else{
			
				exit(json_encode(array('status'=>0,'msg'=>'已经有上级')));
			
			}
		}else{
			
			exit(json_encode(array('status'=>0,'msg'=>'自己不能成为自己上级')));
			
		}
		//查询客户当前上级的名称
		$first_leader = M('users')->where(array("open_id"=>$open_id))->getField("first_leader");
		$nick_name = M('users')->where(array("user_id"=>$first_leader))->getField("nick_name");
		exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('nick_name'=>$nick_name))));
	}
	
	
	public function is_distribut(){
		
		$open_id = $_GET['openid'];
		$is_distribut = M('users')->where(array("open_id"=>$open_id,"is_distribut"=>1))->getField("user_id");
		
		//不是分销商的客户，如果后台设置 默认都是分销商，则
		
        $distribut_condition = tpCache('distribut.condition'); 
        if($distribut_condition == 0)  // 直接成为分销商, 每个人都可以做分销        
			 M('users')->where(array("open_id"=>$open_id))->save(array("is_distribut"=>1));	

		
		$need = tpCache('distribut.need'); // 需要购买产品的ID
		if(!empty($is_distribut)){
			
			exit(json_encode(array('status'=>1,'need'=>$need)));
		}else{
			exit(json_encode(array('status'=>0,'need'=>$need)));
		}	
	}
	 public function withdrawals(){
		$user_id = intval($_GET['user_id']);

		$money = intval($_GET['money']);
		
			$wechat = $_GET['wechat'];
			$zhifubao = $_GET['zhifubao'];
			
			
			$data['bank_name'] = $wechat;
			$data['account_bank'] = $zhifubao;
			$data['user_id'] = $user_id;
			$data['money']=$money;		
            $data['create_time'] = time();

			$distribut_min = tpCache('distribut.min'); // 最少提现额度
			$user_money=M("users")->where("user_id=".$user_id)->getField("user_money");
            if($data['money'] < $distribut_min)
            {
					exit(json_encode(array('status'=>0,'msg'=>'获取成功','result'=>array('message'=>'不能低于'.$distribut_min,'元'))));
            }
			
            if($data['money'] > $user_money)
            {
				
				exit(json_encode(array('status'=>0,'msg'=>'获取成功','result'=>array('message'=>"不能大于".$user_money."元."))));

            }

            if(M('withdrawals')->add($data)){
				
					exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('message'=>"提现成功"))));
            }else{
               exit(json_encode(array('status'=>0,'msg'=>'获取成功','result'=>array('message'=>"提现 失败联系客服"))));
            }		
		 
	 }	
	
	
    /*
     * 编辑地址
     */
    public function editAddress(){
    
    	
    	//echo $address_id;
    	$object = file_get_contents('php://input');
    	$_POST = (json_decode($object, true));
    	
    	$address_id = $_POST['address_id'];
        $this->user_id = $_POST['user_id'];
        //echo $this->user_id.'1';
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        
        //echo $address_id;
        
        //echo $_POST['address'];
        M('user_address')->where(array("address_id"=>$address_id))->save(array("address"=>$_POST['address'],"mobile"=>$_POST['mobile'],'zipcode'=>$_POST['zipcode'],'consignee'=>$_POST['consignee'],'province'=>$_POST['province'],'city'=>$_POST['city'],'district'=>$_POST['district']));
        exit(json_encode(array('status'=>1,'msg'=>'成功','result'=>'')));
    }
    
    
    /*
     * 地址删除
     */
    public function del_address(){
        $id = I('id');
        $this->user_id = I('user_id');
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $address = M('user_address')->where("address_id = $id")->find();
        $row = M('user_address')->where(array('user_id'=>$this->user_id,'address_id'=>$id))->delete();                
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if($address['is_default'] == 1)
        {
            $address = M('user_address')->where("user_id = {$this->user_id}")->find();            
            M('user_address')->where("address_id = {$address['address_id']}")->save(array('is_default'=>1));
        }        
        if($row)
           exit(json_encode(array('status'=>1,'msg'=>'删除成功','result'=>''))); 
        else
           exit(json_encode(array('status'=>1,'msg'=>'删除失败','result'=>''))); 
    } 
    
    /*
     * 地址删除
     */
    public function get_address(){
    	$id = I('id');
    	$this->user_id = I('user_id');
    	if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
    	$address = M('user_address')->where("address_id = $id")->find();
    	$address['cityvalue'] = $address['city'];
    	$address['city'] = M('region')->where(array("id"=>$address['province']))->getField('name').M('region')->where(array("id"=>$address['city']))->getField('name').M('region')->where(array("id"=>$address['district']))->getField('name');
  
    	exit(json_encode(array('status'=>1,'msg'=>'删除失败','result'=>$address)));
    }
    
    
    /*
     * 设置默认收货地址
     */
    public function setDefaultAddress(){
//        $user_id = I('user_id',0);
    	$this->user_id = I('user_id',0);
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $address_id = I('address_id',0);
        $data = $this->userLogic->set_default($this->user_id,$address_id); // 获取用户信息
        if(!$data)
            exit(json_encode(array('status'=>-1,'msg'=>'操作失败','result'=>'')));
        exit(json_encode(array('status'=>1,'msg'=>'操作成功','result'=>'')));
    }

    /*
     * 获取优惠券列表
     */
    public function getCouponList(){
        $this->user_id = I('user_id',0); // 当前登录用户的ID
        $p = I('page',0);
        if(!$this->user_id) {
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
        }
        $data = $this->userLogic->get_coupon($this->user_id,$_REQUEST['type'],$p);
        foreach ($data['result'] as $k=>$v){
        	$data['result'][$k]['use_end_time'] = date("Y-m-d ",$v['use_end_time']);
        	$data['result'][$k]['use_start_time'] = date("Y-m-d ",$v['use_start_time']);
        }
        unset($data['show']);
        exit(json_encode($data));
    }
    //获取领券中心的优惠券列表
    public function getReceiveCoupon(){
    	$this->user_id = I('user_id',0);
        if(!$this->user_id)
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误')));
        // 获取优惠券的信息
        $coupon = M('coupon')->where(array('type'=>4,'use_end_time'=>array('gt',time())))->order("id desc")->select();
        if ($coupon) {
            //设置优惠券的状态 1:已领取,2:未领取,3:已领完
            foreach ($coupon as $k=>$v) {
                $coupon[$k]['use_start_time'] = date('Y-m-d', $v['use_start_time']);
                $coupon[$k]['use_end_time'] = date('Y-m-d', $v['use_end_time']);
                $user_coupon = M('coupon_list')->where(array('cid'=>$v['id'],'uid'=>$this->user_id))->find();
                if ($user_coupon) {
                    $coupon[$k]['c_status'] = '1';
                } else {
                    $remain_coupon = M('coupon_list')->where(array('cid'=>$v['id'],'uid'=>0))->find();
                    if ($remain_coupon) {
                        $coupon[$k]['c_status'] = '2';
                    } else {
                        $coupon[$k]['c_status'] = '3';
                    }
                }
                //  20181018 根据店铺ID查询店铺名称 亮 START
                $store_name = M('Store')->where(array('store_id'=>$coupon[$k][store_id]))->field("store_name,store_id")->find();
                $coupon[$k]['store_name'] = $store_name['store_name'];
                //  20181018 根据店铺ID查询店铺名称 亮 END
				
				
            }
				//20181110  判断是否启用多店铺 便于审核  jun
				$basic=tpCache("basic");
				$is_show_store=$basic['app_test'];
				//20181110  判断是否启用多店铺 便于审核  jun
            exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$coupon,'is_show_store'=>$is_show_store)));
        } else {
            exit(json_encode(array('status'=>-1,'msg'=>'获取失败')));
        }
    }
    
    //领取优惠券
    public function receiveCoupon() {
    	$this->user_id = I('user_id',0);
    	$cid = I('id');
            if(!$this->user_id)
                exit(json_encode(array('status'=>-1,'msg'=>'参数有误')));
        // 线下代金券 维亚轩 青 2019-4-17 15:15:16
        $the_coupon = M("coupon")->where(array('id'=>$cid))->find();
        if ($the_coupon['type'] == 4 && $the_coupon['use_start_time'] < time() && $the_coupon['use_end_time'] > time()) {
            $code = I('code');
            $id = M("coupon_list")->where(array('code'=>$code,'uid'=>0))->getField('id');
            if ($id) {
                M('coupon_list')->where(array('id'=>$id))->save(array('uid'=>$this->user_id));
                $coupon = M('coupon')->where(array('id'=>$cid))->find();
                exit(json_encode(array('status'=>1,'msg'=>'领取成功', 'list'=>$coupon)));
            }else{
                exit(json_encode(array('status'=>-1,'msg'=>'该优惠券已被领取')));
            }
        }else{
            //判断是否能领取
            $key = M('coupon_list')->where(array('cid'=>$cid,'uid'=>$this->user_id))->find();
            if ($key) {
                exit(json_encode(array('status'=>-1,'msg'=>'您已经领取过了')));
            }
            $id = M('coupon_list')->where(array('cid'=>$cid, 'uid'=>0))->getField('id');
            if($id) {
                M('coupon_list')->where(array('id'=>$id))->save(array('uid'=>$this->user_id));
                $coupon = M('coupon')->where(array('id'=>$cid))->find();
                exit(json_encode(array('status'=>1,'msg'=>'领取成功', 'list'=>$coupon)));
            } else {
                exit(json_encode(array('status'=>-1,'msg'=>'该优惠券已领取完')));
            }
        }
    }
    
    /*
     * 获取商品收藏列表
     */
    public function getGoodsCollect(){
        $this->user_id = I('user_id',0);
        $page = I("page",0);
        $keyword = I("keyword");
        //if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $data = $this->userLogic->get_goods_collect($this->user_id,$page,$keyword);
        foreach($data['result'] as $key=>$value){
        	
        		$data['result'][$key]['image'] = C('MYOSS')['url'].$value['original_img'];
        	
        }
        unset($data['show']);
        exit(json_encode($data));
    }
    /*
     * 获取店铺收藏列表
     */
    public function getStoreCollect(){
        $this->user_id = I('user_id',0);
        $page = I("page",0);
        $keyword = I("keyword");
        //if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $data = $this->userLogic->get_store_collect($this->user_id,$page,$keyword);
        foreach($data['result'] as $key=>$value){

            $data['result'][$key]['image'] = C('MYOSS')['url'].$value['store_logo'];
        	
        }
        unset($data['show']);
        exit(json_encode($data));
    }

    /*
     * 获取商品浏览记录列表
     */
    public function getGoodsLiulan(){
        $this->user_id = I('user_id',0);
        $page = I("page",0);
        //if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $data = $this->userLogic->get_goods_liulan($this->user_id,$page);

        foreach($data['result'] as $key=>$value){
            $data['result'][$key]['image'] = C('MYOSS')['url'].$value['original_img'];
        }
        $arr = array();
        $arrr = array();

        foreach($data['result'] as $k=>$v){
            $arr[date('Y年n月j日',$v['add_time'])][] = $v;
        }
        foreach($arr as $k=>$v){
            $arrr[] = array(
                'ymd'   =>  $k,
                'data'  =>  $v,
                );
        }
        $data['result'] = $arrr;
        unset($data['show']);
        exit(json_encode($data));
    }

    /*
     * 用户订单列表
     */
    public function getOrderList()
    {
        $this->user_id = I('user_id', 0);
        if (!$this->user_id) exit(json_encode(array('status' => -1, 'msg' => '缺少参数', 'result' => '')));
        $page = I('page', '');
        $type = I('type', '');
        $keys = I('keys', '');

        if ($type == "NO")
            $type = "";

        $map = " 1=1 ";
        $map .= " and a.user_id = {$this->user_id} ";
        // $map .= " and a.order_status != 3 ";
        $map .= " and b.is_order_refund != 1 ";
        if ($keys)
            $map .= " and (goods_name like '%" . $keys . "%' or order_sn like '%" . $keys . "%' or master_order_sn like '%" . $keys . "%' or store_name like '%" . $keys . "%') ";

        $db_prefix = C('DB_PREFIX');
        if ($type == "AFTERSALE") {
            $count = M('return_goods as a')
                ->field('a.*,b.*,c.store_name')
                ->join($db_prefix . 'goods as b on a.goods_id = b.goods_id', 'LEFT')
                ->join($db_prefix . 'store as c on a.store_id = c.store_id')
                ->group('a.store_id')
                ->where("a.user_id = {$this->user_id}")->count();
            $Page = new \Think\Page($count, 10);

            $show = $Page->show();

            $Page->firstRow = $Page->listRows * $page;

            $order_list = M('return_goods as a')
                ->field('a.*,c.store_name')
                ->join($db_prefix . 'store as c on a.store_id = c.store_id')
                ->group('a.return_order_sn')
                ->where("a.user_id = {$this->user_id}")->order("a.id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else {
            //条件搜索
            if ($type == "FINISH") {
                $map1 = ' AND (order_status=2 or order_status=4  or pay_status=1) ';
                $map = $type ? $map . $map1 : $map;
            } else {
                $map = $type ? $map . C($type) : $map;
            }

            $count = M('order as a')
                ->field('a.*,b.*,c.store_name')
                ->join($db_prefix . 'order_goods as b on b.order_id = a.order_id')
                ->join($db_prefix . 'store as c on a.store_id = c.store_id')
                ->group('a.order_id')->where($map)->select();
            $Page = new \Think\Page(count($count), 10);

            $show = $Page->show();

            $Page->firstRow = $Page->listRows * $page;
            //echo $page;
            //echo $Page->firstRow;

            $order_list = M('order as a')
                ->field('a.*,b.*,c.store_name')
                ->join($db_prefix . 'order_goods  as  b  on b.order_id = a.order_id')
                ->join($db_prefix . 'store as c on a.store_id = c.store_id')
                ->group('a.order_id')
                ->where($map)->order("a.order_id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        }

        //获取订单商品
        foreach ($order_list as $k => $v) {


            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            $order_list[$k]['order_amount'] += $v['yijia_heji'];
            $order_list[$k]['total_amount'] += $v['yijia_heji'];
            $order_list[$k]['goods_price'] += $v['yijia_heji'];

            $order_list[$k]['order_amount'] = geshi($order_list[$k]['order_amount']);
            $order_list[$k]['total_amount'] = geshi($order_list[$k]['total_amount']);
            $order_list[$k]['goods_price'] = geshi($order_list[$k]['goods_price']);

            $logistics_state = 1;
            if (!empty($v['driver_time'])){
                $logistics_state = 5;
            }elseif (!empty($v['driver_id'])){
                $logistics_state = 3;
            }elseif (!empty($v['ruku_count'])){
                $logistics_state = 2;
            }


            //添加订单状态
            $order_list[$k]['logistics_state'] =  $logistics_state;
            $order_list[$k]['logistics_state_array'] = $this->logistics_state_array;


            //订单总额
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount'];
            if ($type == "AFTERSALE") {

                $goods_list = M('return_goods as a')
                    ->field('a.*,b.goods_name,b.original_img')
                    ->join($db_prefix . 'goods as b on a.goods_id = b.goods_id', 'LEFT')
                    ->where("a.user_id = {$this->user_id} and a.return_order_sn={$v['return_order_sn']}")->order("a.id desc")->select();
                foreach ($goods_list as $key => $value) {
                    $goods_list[$key]['heji'] = \sanwei(($value['member_goods_price'] + $value['yijia']) * $value['goods_num']);
                    $goods_list[$key]['shijian'] = date('Y/m/d H:i', $value['addtime']);
                }
                $data['result'] = $goods_list;

            } else {
                $data = $this->userLogic->get_order_goods($v['order_id']);
            }

            foreach ($data['result'] as $key => $value) {
                $data['result'][$key]['image'] = C('MYOSS')['url'] . $value['original_img'];
            }

            $order_list[$k]['goods_list'] = $data['result'];

        }

        exit(json_encode(array('status' => 1, 'msg' => '获取成功', 'result' => $order_list, 'aaa' => $map)));
    }
    /*
     * 获取订单详情
     */
    public function getOrderDetail()
    {
        $this->user_id = I('user_id', 0);
        if (!$this->user_id) exit(json_encode(array('status' => -1, 'msg' => '缺少参数', 'result' => '')));
        $id = I('id');
        if (I('id')) {
            $map['order_id'] = $id;
        } else {
            $map['order_sn'] = I('sn');
        }
        $map['a.user_id'] = $this->user_id;
        $order_info = M('order a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id', 'LEFT')
            ->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        $order_info['order_amount'] += $order_info['yijia_heji'];
        $order_info['total_amount'] += $order_info['yijia_heji'];
        $order_info['goods_price'] += $order_info['yijia_heji'];

        $order_info['order_amount'] = geshi($order_info['order_amount']);
        $order_info['total_amount'] = geshi($order_info['total_amount']);
        $order_info['goods_price'] = geshi($order_info['goods_price']);

        //echo \json_encode($order_info);exit;
        if (!$this->user_id > 0)
            exit(json_encode(array('status' => -1, 'msg' => '参数有误', 'result' => '')));
        if (!$order_info) {
            exit(json_encode(array('status' => -1, 'msg' => '订单不存在', 'result' => '')));
        }

        $invoice_no = M('DeliveryDoc')->where("order_id = $id")->getField('invoice_no', true);
        $shipping_name = M('DeliveryDoc')->where("order_id = $id")->getField('shipping_name', true);
        if (!empty($invoice_no)) {
            $order_info['invoice_no'] = implode(' , ', $invoice_no);
            $order_info['shipping_name'] = implode(' , ', $shipping_name);
        } else {
            $order_info['invoice_no'] = "未发货";
            $order_info['shipping_name'] = "未发货";
        }
        // 获取 最新的 一次发货时间
        $order_info['shipping_time'] = M('DeliveryDoc')->where("order_id = $id")->order('id desc')->getField('create_time');

        //获取订单商品
        $data = $this->userLogic->get_order_goods($order_info['order_id']);
//        dump($data);exit;
        $order_info['num'] = count($data['result']);

        $order_info['add_time'] = date('Y-m-d H:i', $order_info['add_time']);
        foreach ($data['result'] as $key => $value) {
            if ($order_info['order_status'] == 4 || ($order_info['shipping_status'] == 0 && $order_info['pay_status'] == 1) || $order_info['order_status'] == 2 || ($order_info['shipping_status'] == 1 && $order_info['pay_status'] == 1 && $order_info['shipping_status'] == 1)) {
                $data['result'][$key]['order_refund_enable'] = 1;
            }
            $return_num = M('return_goods')->where(['order_id'=>$value['order_id'],'goods_id'=>$value['goods_id'],'spec_key'=>$value['spec_key']])->sum('goods_num');
            $data['result'][$key]['return_max'] = $data['result'][$key]['goods_num']-$return_num;
            $data['result'][$key]['image'] = C('MYOSS')['url'] . $value['original_img'];
        }

        $order_info['goods_list'] = $data['result'];


        if ($order_info['shipping_price'] == "null") {

            $order_info['shipping_price'] = "0.00";
        }
        if (!empty($order_info['driver_id'])) {
            $driver = M('users')->where(['user_id' => $order_info['driver_id']])->find();
            $order_info['driver_name'] = $driver['nick_name'];
            $order_info['driver_mobile'] = $driver['mobile'];
        } else {
            $order_info['driver_name'] = '';
            $order_info['driver_mobile'] = '';
        }
        $api = "https://imessage.zczmer.com/api/user/getStoreUid";
        $params = [
            'platform_id' => "3",
            'application_id' => "5",
            'store_id' => $order_info['store_id'],
            'user_id'=>$this->user_id
        ];
        $response = httpRequest($api, 'post' ,$params);
        // dump($response);
        $res = json_decode($response,true);
        if($res['code']==1){
            $order_info['uid'] = $res['result'];
        }
        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];
        exit(json_encode(array('status' => 1, 'msg' => '获取成功', 'result' => $order_info)));
    }

    /**
     * 点击申请售后获取商品信息
     */
    public function getgoodsInfo()
    {
        $this->user_id = I('user_id',0);
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
        $id = I('id');
        if(I('id')){
            $map['order_id'] = $id;
        }else{
            $map['order_sn'] = I('sn');
        }
        $goods_id = I('goods_id','');
        //从点击点击申请退款按钮提交过来
        if ($goods_id){
            $map['user_id'] = $this->user_id;
            $map['goods_id'] = $goods_id;
            $Model = new \Think\Model();
            $sql = "SELECT og.*,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE order_id = ".$id." and og.goods_id =".$goods_id;
            $goods_list = $Model->query($sql);
            $order_info = M('order')->where($map)->find();

            foreach ($goods_list as $k=>$v)
            {
                $goods_list[$k]['image'] = SITE_URL.$v['original_img'];
            }
            $order_info['goods_list']=$goods_list[0];
            exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$order_info)));
        }
    }

    /**
     * 申请售后上传的图片
     */
    public function upload_image()
    {
        //得到传输的数据
        $file = $_FILES['image'];

        //得到文件名称
        $name = $file['name'];

        $type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型，并且都转化成小写

        $allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型
       //判断文件类型是否被允许上传
        if(!in_array($type, $allow_type)){
            //如果不被允许，则直接停止程序运行
            return ;
        }

       //判断是否是通过HTTP POST上传的
        if(!is_uploaded_file($file['tmp_name'])){
            //如果不是通过HTTP POST上传的
            return ;
        }
        $upload_path = "./Public/images/after_sale_picture/"; //上传文件的存放路径
        if (!file_exists($upload_path)){
            mkdir ($upload_path,0777,true);//不存在 创建新文件夹
        }
        $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
        $rand = substr($randStr,0,6);
        $name = date('YmdHis').$rand.".".$type;
         //开始移动文件到相应的文件夹
        if(move_uploaded_file($file['tmp_name'],$upload_path.$name)){
            $path = substr($upload_path.$name,1);
           $data = json_encode(array("code"=>0,"url"=>$path));
          echo $data;
        }else{
            echo "Failed!";
        }
    }

    /**
     * 退货退款,换货
     */
    public function refund()
    {
		//echo 'asdfasdf';exit;
       $data = $_REQUEST;
        $order_id =$data['order_id'] ;
        $goods_id = $data['goods_id'];
        $type = $data['type'];
        $model=M('return_goods');
        if ($type == 0){
            //说明提交过来的有可能为退款退货，或者仅退货
            $sql = "select c1.* from __PREFIX__order as c1 
                      join __PREFIX__order_goods as c2  on c1.order_id = c2.order_id 
                     where c1.order_id = ".$order_id." and  c2.goods_id = ".$goods_id ;
            $order_list = $model->query($sql);
            //根据商品id和订单id查询商品是否为已支付未发货状态，如果是，将type改为退款，否则为退款退货
            if($order_list[0]['shipping_status'] ==0 && $order_list[0]['pay_status']==1){
                $data['type']=2;
            }
        }

        $sql = "select c1.order_sn,c1.user_id,c2.store_id,c2.spec_key,c2.goods_num,c2.member_goods_price,c3.points from __PREFIX__order as c1 
                      join __PREFIX__order_goods as c2  on c1.order_id = c2.order_id
					   join __PREFIX__goods as c3  on c2.goods_id = c3.goods_id 
                     where c1.order_id = ".$order_id." and  c2.goods_id = ".$goods_id."  order by c1.order_id DESC " ;
        $order_field = $model->query($sql);

        $order_field[0]['addtime']=time();
       $data= array_merge($data,$order_field[0]);

        $res = M('order_goods')->where("order_id = {$order_id} and goods_id = {$goods_id}")->save(array("is_order_refund" => 1));
        if (!$res){
            echo json_encode(array("code"=>1,"msg"=>"申请失败"));
            exit;
        }
         $res =  M('return_goods')->add($data);
         if ($res){
             echo json_encode(array("code"=>0,"msg"=>"申请成功","confirm"=>1));
         }else{
             echo json_encode(array("code"=>1,"msg"=>"申请失败"));
         }

    }

    public function refund_detail()
    {
                $data = $_REQUEST;
                $order_id=$data['order_id'] ;
                $goods_id = $data['goods_id'];
              $sql = "select c1.* ,c2.goods_num,c2.goods_name,c2.goods_price,c3.original_img from __PREFIX__return_goods as c1 
                      join __PREFIX__order_goods as c2  on c1.order_id = c2.order_id and c1.goods_id =c2.goods_id
                     left join __PREFIX__goods as c3 on c1.goods_id =c3.goods_id 
                     where c1.order_id = ".$order_id." and  c1.goods_id = ".$goods_id."  order by c1.order_id DESC " ;
              $order_list = M()->query($sql);

              foreach ($order_list as  $k =>$v){
                  $order_list[$k]['image'] = SITE_URL.$v['original_img'];
                  $order_list[$k]['image_list'] =json_decode( $v['imgs']);
                  foreach ( $order_list[$k]['image_list'] as $kk =>$vv){
                      $order_list[$k]['image_list'][$kk] = SITE_URL.$vv;
                  }
              }
              if ($order_list[0]['status']==1){
                  $order_list[0]['address'] =   M('store')->where(array('store_id'=>$order_list[0]['store_id']))->getField('store_address');
              }

              $res = array("code"=>0,"data"=>$order_list[0]);
              echo json_encode($res);
    }

    //获取物流信息
    public function getShippingInfo() {
		
    	require_once './Public/plugins/jisukuaidi/curl.func.php';
	
    	$order_id = I('order_id');
		$order = M('delivery_doc')->where(array('order_id'=>$order_id))->find();
		if (!$order) {
			exit(json_encode(array('status'=>-1,'msg'=>'请等待发货')));
		}

		$appkey = '0a95d7b70c96aadf2c3d2ff1adccf161'; //你的appkey
		
		$url = "https://api.shenjian.io/express/query?appid=$appkey";
		
		//$type = 'auto';
		$number = $order['invoice_no'];
	 
		$url =$url."&number=$number";

		$result = doGet($url);
		
		$jsonarr = json_decode($result, true);

		//设置传递的信息
		switch ($jsonarr['data']['result']['deliverystatus'])
		{
		case 1:
			$jsonarr['data']['result']['status_text'] = '在途中';
			break;
		case 2:
			$jsonarr['data']['result']['status_text'] = '派送中';
			break;
		case 3:
			$jsonarr['data']['result']['status_text'] = '已签收';
			break;
		case 4:
			$jsonarr['data']['result']['status_text'] = '已签收';
			break;
		}
		//exit(var_dump($jsonarr));
	 
		if($jsonarr['error_code'] != 0)
		{
			exit(json_encode(array('status'=>-1,'msg'=>$jsonarr['msg'])));
		}
	 
		exit(json_encode(array('status'=>1,'msg'=>'ok', 'result'=>$jsonarr['data']['result'])));
    }

    /**
     * 取消订单
     */
    public function cancelOrder(){
        $id = I('order_id');
        $this->user_id = I('user_id',0);
        if(!$this->user_id > 0 || !$id > 0)
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
            
           
        $data = $this->userLogic->cancel_order($this->user_id,$id);
        exit(json_encode($data));
    }
    /**
     * 再次架构
     */
    public function jiagou(){
        $id = I('order_id');
        $this->user_id = I('user_id',0);
        if(!$this->user_id > 0 || !$id > 0)
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
        $data = $this->userLogic->jiagou($this->user_id,$id);
        exit(json_encode($data));
    }
    /**
     * 发送手机注册验证码
     * http://www.we10.cn/index.php?m=Api&c=User&a=send_sms_reg_code&mobile=13800138006&unique_id=123456
     */
    public function send_sms_reg_code(){
        $mobile = I('mobile');     
        $unique_id = I('unique_id');
        if(!check_mobile($mobile))
            exit(json_encode(array('status'=>-1,'msg'=>'手机号码格式有误')));
        $code =  rand(1000,9999);
        $send = $this->userLogic->sms_log($mobile,$code,$unique_id);
        if($send['status'] != 1)
            exit(json_encode(array('status'=>-1,'msg'=>$send['msg'])));
        exit(json_encode(array('status'=>1,'msg'=>'验证码已发送，请注意查收')));
    }    

    /**
     *  收货确认
     */
    public function orderConfirm(){
        $id = I('order_id',0);
        $this->user_id = I('user_id',0);
        if(!$this->user_id || !$id)
            exit(json_encode(array('status'=>-1,'msg'=>'参数有误','result'=>'')));
        $data = confirm_order($id,$this->user_id);            
        exit(json_encode($data));
    }
    public function comments(){
    	/*
    	 * 
    	 * 
    	 *$user_id = $this->user_id;
        $status = I('get.status');
        $logic = new UsersLogic();
        $result = $logic->get_comment($user_id, $status); //获取评论列表
        $this->assign('comment_list', $result['result']);
        if ($_GET['is_ajax']) {
            $this->display('ajax_comment_list');
            exit;
        }
        $this->display();shadow
    	 */
		exit;
    	$this->user_id = I('user_id',0);
    	$p = I('page',0);
    	
    	$status = I('get.status');
    	$logic = new UsersLogic();
    	$result = $logic->get_comment($this->user_id , $status,$p); //获取评论列表
    	
    	//$count = M('comment')->where(array("user_id"=>$this->user_id))->count();
    	//$page = new \Think\Page($count,10);
    	//$page->firstRow = $page->listRows * $p;
    	$datas = $result['result'];//M('comment')->where(array("user_id"=>$this->user_id))->limit("{$page->firstRow},{$page->listRows}")->select();
    	
    	foreach ($datas as $key=>$value)
    	{
    		$datas[$key] = array_merge(M('goods')->where(array("goods_id"=>$value['goods_id']))->find(),$value);
    		$datas[$key]['image'] = SITE_URL.$datas[$key]['original_img'];
    		$datas[$key]['add_time'] = date("Y-m-d H:i:s",$datas[$key]['add_time']);
    		$comment = M('comment')->where(array("goods_id"=>$datas[$key]['goods_id'],"order_id"=>$datas[$key]['order_id']))->find();
    		if($comment)
    		{
    			$datas[$key]['service_rank'] = $comment['service_rank'];
    			$datas[$key]['content'] = $comment['content'];
    		}
    	}
    	
    	
    	if(!$datas)
    		exit(json_encode(array('status'=>-1,'msg'=>'操作失败','result'=>'')));
    	exit(json_encode(array('status'=>1,'msg'=>'操作成功','result'=>$datas)));
    }
    
    /*
     *添加评论
     */
    public function add_comment(){
      
//            // 晒图片
//            if($_FILES[img_file][tmp_name][0])
//            {
//                    $upload = new \Think\Upload();// 实例化上传类
//                    $upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
//                    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
//                    $upload->rootPath  =     './Public/upload/comment/'; // 设置附件上传根目录
//                    $upload->replace  =     true; // 存在同名文件是否是覆盖，默认为false
//                    //$upload->saveName  =   'file_'.$id; // 存在同名文件是否是覆盖，默认为false
//                    // 上传文件
//                    $info   =   $upload->upload();
//                    if(!$info) {// 上传错误提示错误信息
//                        exit(json_encode(array('status'=>-1,'msg'=>$upload->getError()))); //$this->error($upload->getError());
//                    }else{
//                        foreach($info as $key => $val)
//                        {
//                            $comment_img[] = '/Public/upload/comment/'.$val['savepath'].$val['savename'];
//                        }
//                        $comment_img = serialize($comment_img); // 上传的图片文件
//                    }
//            }
            
            //$unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
            $this->user_id = I('user_id'); // 用户id
            $user_info = M('users')->where("user_id = {$this->user_id}")->find();

             $goods_id = I('goods_id');
            $add['goods_id'] = $goods_id;
            $store_id  =M('goods')->where("goods_id = {$goods_id}")->getField('store_id');
            $add['store_id'] = $store_id;

            $add['email'] = $user_info['email'];
            $add['head_pic'] = $user_info['head_pic'];
            $add['username'] = $user_info['nick_name'];
            $add['order_id'] = I('order_id');
            $add['service_rank'] = I('service_rank');
            $add['deliver_rank'] = I('deliver_rank');
            $add['goods_rank'] = I('goods_rank');
//            $add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = I('content');
            $add['img'] = htmlspecialchars_decode(I('img'));

            $add['add_time'] = time();
            $add['ip_address'] = $_SERVER['REMOTE_ADDR'];
            $add['user_id'] = $this->user_id;  
			$add['store_id'] = M('goods')->where("goods_id = {$add['goods_id']}")->getField("store_id");
	    
            //添加评论
            $row = $this->userLogic->add_comment($add);
            exit(json_encode($row));
    }  
    
    /*
     * 账户资金
     */
    public function account(){
        
        $this->user_id = I("user_id"); // 唯一id  类似于 pc 端的session id
       // $user_id = I('user_id'); // 用户id
        //获取账户资金记录
        $page = I("page",0);
        $data = $this->userLogic->get_account_log($this->user_id,I('get.type'),$page);
        $account_log = $data['result'];
        
        foreach ($account_log as $key=>$value)
        {
        	$account_log[$key]['change_time'] = date("Y-m-d h:i:s",$value['change_time']);
        }
        
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$account_log)));
    }    
    
    /**
     * 退换货列表
     */
    public function return_goods_list()
    {        
        
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
       // $user_id = I('user_id'); // 用户id       
        $count = M('return_goods')->where("user_id = {$this->user_id}")->count();        
        $page = new \Think\Page($count,4);
        $list = M('return_goods')->where("user_id = {$this->user_id}")->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');
        if(!empty($goods_id_arr))
            $goodsList = M('goods')->where("goods_id in (".  implode(',',$goods_id_arr).")")->getField('goods_id,goods_name');        
        foreach ($list as $key => $val)
        {
            $val['goods_name'] = $goodsList[$val[goods_id]];
            $list[$key] = $val;
        }
        //$this->assign('page', $page->show());// 赋值分页输出                    	    	
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$list)));
    }    
    
    
    /**
     *  售后 详情
     */
    public function return_goods_info()
    {
        $id = I('id',0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        if($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);        
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();                
        $return_goods['goods_name'] = $goods['goods_name'];
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$return_goods)));
    }    
    
    
    /**
     * 申请退货状态
     */
    public function return_goods_status()
    {
        $order_id = I('order_id',0);        
        $goods_id = I('goods_id',0);
        $spec_key = I('spec_key','');
        
        $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id and spec_key = '$spec_key' and status in(0,1)")->find();            
        if(!empty($return_goods))        
            exit(json_encode(array('status'=>1,'msg'=>'已经在申请退货中..','result'=>$return_goods['id']))); 
         else
             exit(json_encode(array('status'=>1,'msg'=>'可以去申请退货','result'=>-1)));
    }
    /**
     * 申请退货
     */
    public function return_goods()
    {
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        //$user_id = I('user_id'); // 用户id              
        $order_id = I('order_id',0);
        $order_sn = I('order_sn',0);
        $goods_id = I('goods_id',0);
        $type = I('type',0); // 0 退货  1为换货
        $reason = I('reason',''); // 问题描述
        $spec_key = I('spec_key');
		                
        if(empty($order_id) || empty($order_sn) || empty($goods_id)|| empty($this->user_id)|| empty($type)|| empty($reason))
            exit(json_encode(array('status'=>-1,'msg'=>'参数不齐!')));
        
        $c = M('order')->where("order_id = $order_id and user_id = {$this->user_id}")->count();
        if($c == 0)
        {
             exit(json_encode(array('status'=>-3,'msg'=>'非法操作!')));           
        }         
        
        $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id and spec_key = '$spec_key' and status in(0,1)")->find();            
        if(!empty($return_goods))
        {
            exit(json_encode(array('status'=>-2,'msg'=>'已经提交过退货申请!')));
        }       
        if(IS_POST)
        {
            
    		// 晒图片
    		if($_FILES['img_file']['tmp_name'][0])
    		{
    			$upload = new \Think\Upload();// 实例化上传类
    			$upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
    			$upload->exts      =    array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    			$upload->rootPath  =    './Public/upload/return_goods/'; // 设置附件上传根目录
    			$upload->replace   =    true; // 存在同名文件是否是覆盖，默认为false
    			//$upload->saveName  =  'file_'.$id; // 存在同名文件是否是覆盖，默认为false
    			// 上传文件
    			$upinfo  =  $upload->upload();
    			if(!$upinfo) {// 上传错误提示错误信息
    				$this->error($upload->getError());
    			}else{
    				foreach($upinfo as $key => $val)
    				{
    					$return_imgs[] = '/Public/upload/return_goods/'.$val['savepath'].$val['savename'];
    				}
    				$data['imgs'] = implode(',', $return_imgs);// 上传的图片文件
    			}
    		}            
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order_sn; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $this->user_id;            
            $data['type'] = $type; // 服务类型  退货 或者 换货
            $data['reason'] = $reason; // 问题描述            
            $data['spec_key'] = $spec_key; // 商品规格						
            M('return_goods')->add($data);      
            exit(json_encode(array('status'=>1,'msg'=>'申请成功,客服第一时间会帮你处理!')));                        
        }     
    } 

    
    public function validateOpenid()
    {
		$basic=tpCache("basic");
        $open_id = $_GET['openid'];
		$unionId = $_GET['unionId'];
		$reg= $_GET['reg'];
		
		// if($basic['app_test']==0){
			$res = M('users a')
			->field('a.*,b.store_id')
			->join('ty_store b on a.user_id=b.user_id','LEFT')
			->where(array("a.open_id"=>$open_id))->find();
			if(empty($res)){
                $res = M('users')->where(array("user_id"=>61))->find();
            }else{

            }

		// }else{
		// 	$res = M('users a')
		// 	->field('a.*,b.store_id')
		// 	->join('ty_store b on a.user_id=b.user_id','LEFT')
		// 	->where(array("a.open_id"=>$open_id))->find();
		// }
// if(empty($res)){ //审核通过注销。
// 	$res = M('users')->where(array("open_id"=>"undefined"))->find();
// }
      
        if($res){
			$huilv=$this->huilv;
			$res['huilv']= $huilv;
            $res['pay_point_price']=$res['pay_points'];
            $res['pay_points']=$res['pay_points']*$huilv;
			if(strpos($res['head_pic'],'https://') === false){
			 $res['head_pic'] =SITE_URL.$res['head_pic'];
			}
			if(empty($res['unionid'])){
				M('users')->where('user_id='.$res['user_id'])->save([
					'unionid'=>$unionId
				]);
			}
            $tp_config = M('config')->where(array("name"=>'hot_keywords'))->find();
            
            if($tp_config['name'] == 'hot_keywords'){
				$res['hot_keywords'] = explode('|', $tp_config['value']);
			}
			$res['is_show'] =$basic['app_test'];
            $res['phoneNumber'] = $basic['wxtel']; 
			if($res['user_id']==61 && $reg=='yes'){
				echo  json_encode(array("code"=>'400','is_show'=>0,'msg'=>'验证失败。。。',"data"=>$res));exit;
			}
            if($res['is_lock']==1){
				echo  json_encode(array("code"=>'300','is_show'=>0,'msg'=>'待审核中。。。',"data"=>$res));
			}elseif($res['user_id']==61){
				echo  json_encode(array("code"=>'200','is_show'=>0,'msg'=>'验证成功',"data"=>$res));
			}else{
				echo  json_encode(array("code"=>'200','is_show'=>1,'msg'=>'验证成功',"data"=>$res));
			}
            
        }else{
            $res['phoneNumber'] = $basic['wxtel']; 
			echo json_encode(array("code"=>'400','is_show'=>0,'msg'=>'验证失败',"data"=>$res));
		}
            
    }
	
	public  function getopenId(){
		
		$js_code = $_GET['js_code'];
		$paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
		
        $config_value = unserialize($paymentPlugin['config_value']); 
		$APPID=$config_value['appid'];
		$SECRET = $config_value['appsecret'];	
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$APPID}&secret={$SECRET}&js_code={$js_code}&grant_type=authorization_code";
		$timeout = 5;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$json_data = curl_exec($ch);
		curl_close($ch);
		echo  $json_data;
	}	

    
    public function bindPhone(){
    	$user_id = $_GET['user_id'];
    	$phoneNum = $_GET['phone'];
    	$res = M('users')->where(array("user_id"=>$user_id))->save(array("mobile"=>$phoneNum));
    	echo json_encode(array("code"=>'1','msg'=>'验证成功'));
    	 
    }

    public function register()
    {
		$data=array();
    	$data['nickname'] = $_GET['nickname'];
    	$data['nick_name'] = $_GET['nick_name'];
    	$data['head_pic'] = $_GET['head_pic'];
    	$data['mobile'] = $_GET['mobile'];
    	$data['company'] = $_GET['company'];
    	$data['company_address'] = $_GET['company_address'];
    	$data['open_id'] = $_GET['open_id'];
    	$data['p_name'] = $_GET['p_name'];
		$data['store_id'] = 0;
		$data['sex'] = $_GET['sex'];
		$data['doorphoto'] = $_GET['doorphoto'];
		$data['province_id'] = $_GET['province_id'];
		$data['city_id'] = $_GET['city_id'];
		$data['distinguish_id'] = $_GET['district_id'];
		$data['street_id'] = $_GET['street_id'];
		$data['environmentalphotos'] = $_GET['environmentalphotos'];
		$data['reg_time'] = strtotime(date('Y-m-d H:i:s'));
		$user=M('users')->where("mobile=".$_GET['mobile']." and store_id=0")->find();
        
        if(!empty($_GET['street_id'])){
            $street = M('region')->where(['id'=>$_GET['street_id']])->getField('name');
            $data['company_address'] = $street.$_GET['company_address'];
        }
        if(empty($_GET['province_id'])){
            echo json_encode(array("code"=>'400','msg'=>'选择省份'));exit;
        }
        if(empty($_GET['city_id'])){
            echo json_encode(array("code"=>'400','msg'=>'选择城市'));exit;
        }
        if(empty($_GET['district_id'])){
            echo json_encode(array("code"=>'400','msg'=>'选择区'));exit;
        }
         if(empty($data['environmentalphotos'])){
            echo json_encode(array("code"=>'400','msg'=>'缺少环境照片！'));exit;
        }
        if(empty($data['doorphoto'])){
            echo json_encode(array("code"=>'400','msg'=>'缺少门头照！'));exit;
        }
        // if(empty($_GET['parent_id'])){
        //     echo json_encode(array("code"=>'400','msg'=>'缺少业务员！'));exit;
        // }
        
		if(!check_mobile($_GET['mobile'])){
			echo json_encode(array("code"=>'400','msg'=>'手机号码格式有误！'));exit;
		}
		
		$data['fenbu_id'] =0;
		if($_GET['open_id'] && $_GET['parent_id']!='undefined' && $_GET['parent_id']!='null' && isset($_GET['parent_id']))
		{
			$data['parent_id'] = $_GET['parent_id'];
			$where['user_id']=$_GET['parent_id'];
			$first_leader = M('users')->where($where)->find();
			$data['fenbu_id'] =$first_leader['fenbu_id'];
			if($first_leader['is_distribut']>0){
				$data['first_leader'] =intval( $_GET['parent_id']);
				$data['second_leader'] = $first_leader['first_leader'];
				$data['third_leader'] = $first_leader['second_leader'];
			}
		}
		// 成为分销商条件
        $distribut_condition = tpCache('distribut.condition'); 
        if($distribut_condition == 0)  // 直接成为分销商, 每个人都可以做分销
			$data['is_distribut']  = 1;


        if(!empty($user)){
            // M('users')->where("mobile=".$_GET['mobile'])->save(['open_id'=>$data['open_id'],'nick_name'=>$data['nick_name'],'head_pic'=>$data['head_pic']]);
            // $info = [];
            // $info['mobile'] = $data['mobile'];
            // $info['open_id'] = $data['open_id'];
            // $info['old_openid'] = $user['open_id'];
            // $info['user_id'] = $user['user_id'];
            // $info['addtime'] = time();
            // M('useradd')->add($info);
            // $id = $user['user_id'];
			echo json_encode(array("code"=>'400','msg'=>'此电话请勿重复注册！'));exit;
        }else{
            $id = M('users')->add($data);
        }
        
//    	$id = M('users')->add($data);
    	if ($_GET['parent_id']){
    	    //推荐客户注册成功后，返给推荐者的积分
            $points = tpCache('distribut.points');
			
			if($_GET['parent_id']&&($_GET['parent_id']!="null")&&$points){
				accountLog($_GET['parent_id'], 0 , $points , '推荐下级注册赠送积分');
			}
			//如果上级是业务员直接审核通过

            $parent = M('users')->where(array('user_id'=>$_GET['parent_id']))->find();
			if($parent['salesman'] == 1){
                //M('users')->where(array("user_id"=>$id))->save(array("is_lock"=>0));
            }
        }
		
    	$res = M('users')->where(array("user_id"=>$id))->find();
    	$res['head_pic'] = $res['head_pic'];
    	if($res)
    	{
				$pay_points = tpCache('basic.reg_integral');
				if($pay_points > 0)  {
				accountLog($id, 0 , $pay_points , '会员注册赠送积分');
				}
				$tp_config = M('config')->where(array("name"=>'hot_keywords'))->find();
				if($tp_config['name'] == 'hot_keywords')
				$res['hot_keywords'] = explode('|', $tp_config['value']);
				echo json_encode(array("code"=>'200','msg'=>'注册成功，待审核。','res'=>$res));
    	}
    	else
    		echo json_encode(array("code"=>'400','msg'=>'失败'));
    
    }
    

    
    public function getnumber()
    {					
    	$data['encrypteddata'] = str_replace(' ','+',$_GET['encrypteddata']);
		$data['session_key'] = $_GET['session_key'];
		$data['iv'] = $_GET['iv'];
		$data['open_id'] = $_GET['open_id'];
		if($data['encrypteddata']&&$data['session_key']&&$data['iv']){
			require_once 'ThinkPHP/Library/Vendor/Wechataes/wxBizDataCrypt.php';
            error_reporting(E_ERROR);
			$paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
			$config_value = unserialize($paymentPlugin['config_value']); 
			$appid=$config_value['appid'];	
			$iv = $data['iv'];
			$encryptedData=	$data['encrypteddata'];	
            $pc = new \WXBizDataCrypt($appid, $data['session_key']);

			$errCode = $pc->decryptData($encryptedData, $iv, $data_new );

			if ($errCode == 0) {
				$info=json_decode($data_new, true);
			}
				echo $info['phoneNumber'];
		}
	}    
	
    public function getPhoneNumber()
    {					
    	$data['encrypteddata'] = str_replace(' ','+',$_GET['encrypteddata']);
		$data['session_key'] = $_GET['session_key'];
		$data['iv'] = $_GET['iv'];
		$data['open_id'] = $_GET['open_id'];
		if($data['encrypteddata']&&$data['session_key']&&$data['iv']){
			require_once 'ThinkPHP/Library/Vendor/Wechataes/wxBizDataCrypt.php';
            error_reporting(E_ERROR);
			$paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
			$config_value = unserialize($paymentPlugin['config_value']); 
			$appid=$config_value['appid'];	
			$iv = $data['iv'];
			$encryptedData=	$data['encrypteddata'];	
            $pc = new \WXBizDataCrypt($appid, $data['session_key']);

			$errCode = $pc->decryptData($encryptedData, $iv, $data_new );


			if ($errCode == 0) {
				$info=json_decode($data_new, true);
			}
			//\print_r($info);
			if($info)
			{	   
				 $phone_num=$info['phoneNumber'];
				 $res=M('users')->where(array("open_id"=>$_GET['open_id']))->save(array("mobile"=>$phone_num));
				 echo  1;
			}else{
				echo  0;
			}
		}
	}    
	
    function test($url,$id) {    
    	$header = array("Connection: Keep-Alive", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3", "User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:29.0) Gecko/20100101 Firefox/29.0");
    
    	$ch = curl_init();
    
    	curl_setopt($ch, CURLOPT_URL, $url);
    
    	curl_setopt($ch, CURLOPT_HEADER, $v);
    
    	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    	curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    
    
    	$content = curl_exec($ch);
    
    	$curlinfo = curl_getinfo($ch);
    
    	//echo "string";
    
    	//print_r($curlinfo);
    
    	//关闭连接
    
    	curl_close($ch);
    
    
    	if ($curlinfo['http_code'] == 200) {
    
    		if ($curlinfo['content_type'] == 'image/jpeg') {
    
    			$exf = '.jpg';
    
    		} else if ($curlinfo['content_type'] == 'image/png') {
    
    			$exf = '.png';
    
    		} else if ($curlinfo['content_type'] == 'image/gif') {
    
    			$exf = '.gif';
    
    		}
    
    		//存放图片的路径及图片名称  *****这里注意 你的文件夹是否有创建文件的权限 chomd -R 777 mywenjian
    
    		$filename = "Public/head/".$id . $exf;//这里默认是当前文件夹，可以加路径的 可以改为$filepath = '../'.$filename
    
    		$res = file_put_contents($filename, $content);//同样这里就可以改为$res = file_put_contents($filepath, $content);
    
    		$filename = "/".$filename;
    		
    		M('users')->where(array("user_id"=>$id))->save(array("head_pic"=>$filename));
    	}
    
    }
    
	public function Keys_list()
	{
			$key=urldecode(trim(I('key','')));
			if($key){
			$res=M()->query("SELECT left(t.keyword,20) keyword,t.click FROM (SELECT keyword,click FROM ty_user_record force index(keyword) where keyword like'$key%' order by click desc limit 55) as t group by t.keyword");
			$xianshu=12;
			foreach($res as $kk=>$v){
				$pd=M('store')->where('store_name like "'.$v['keyword'].'%"')->getField('store_id');
				if($pd){ 
					$a1[]=[
						'types'=>1,
						'keyword'=>$v['keyword'],
						'pic'=>'/images/dplist.png',
						'click'=>$v['click']+1890
					];
					$res[$kk]['types']=0;
					$res[$kk]['pic']='/images/search.png';
					$res[$kk]['click']=$v['click']+1890;
				}else{
					$res[$kk]['types']=0;
					$res[$kk]['pic']='/images/search.png';
					$res[$kk]['click']=$v['click']+1890;
				}
				
				if($kk>$xianshu){
					unset($res[$kk]);
				}
			}
			$data=empty(array_merge($a1,$res)) ? $res : array_merge($a1,$res);
				foreach($data as $key=>$vs){
					if($key>$xianshu)
					unset($data[$key]);
				}
			}
			echo  json_encode(array("code"=>'200',"data"=>$data));
	}
    
    public function getHotKeywords()
    {
			$uid=urldecode(trim(I('uid','')));
    		$tp_config = M('config')->where(array("name"=>'hot_keywords'))->find();
			$keyword_log=M('user_record')->where(array("user_id"=>$uid))->limit(15)->order('id desc')->select();
    		if($tp_config['name'] == 'hot_keywords'){
				$basic=tpCache("basic");
				$is_show_store=$basic['app_test'];
				$res['hot_keywords'] = explode('|', $tp_config['value']);
				$res['keyword_log']=$keyword_log;
				$res['is_show_store']=$is_show_store;
				$is_show=$uid=='61' ? 0 : 1;
			}
    		echo  json_encode(array("code"=>'200','is_show'=>$is_show,'msg'=>'验证成功',"data"=>$res));
    }
	
    public function logoutWX(){
    	
    	$open_id = $_GET['openid'];
    	
    	if($open_id == null)
    	{
    		echo json_encode(array("code"=>'400','msg'=>'非法参数'));
    		exit();
    	}
    	
    	
    	$res = 1;///D('phone_captcha')->where(array("phone"=>$phone,'captcha'=>$num))->find();
    	if($res)
    	{
    		$res = M('users')->where(array("open_id"=>$open_id))->save(array("open_id"=>'',"openid"=>'','oauth'=>''));
    	
    	
    		if($res)
    		{
    			echo json_encode(array("code"=>'200','msg'=>'注销成功','res'=>$res));
    		}
    		else
    			echo json_encode(array("code"=>'400','msg'=>'注销有误,请稍后重试'));
    	}
    	else
    		echo json_encode(array("code"=>'400','msg'=>'验证码或者手机号码有误'));
    }
    
    public function validate()
    {
        $phone = $_GET['phone'];
        $num = $_GET['num'];
        $open_id = $_GET['openid'];
    
        if($open_id == null)
        {
            echo json_encode(array("code"=>'400','msg'=>'非法参数'));
            exit();
        }
        if($phone == null || strlen($phone) != 11)
        {
            echo json_encode(array("code"=>'400','msg'=>'手机号码输入有误'));
            exit();
        }
        
        
        $res = 1;///D('phone_captcha')->where(array("phone"=>$phone,'captcha'=>$num))->find();
        if($res)
        {
            $res = M('users')->where(array("mobile"=>$phone))->save(array("open_id"=>$open_id,"openid"=>$open_id,'oauth'=>'weixin'));
            
            
            if($res)
            {
            	$res = M('users')->where(array("open_id"=>$open_id))->find();
                echo json_encode(array("code"=>'200','msg'=>'登录成功','res'=>$res));
            }
            else
                echo json_encode(array("code"=>'400','msg'=>'手机号码有误'));
        }
        else
            echo json_encode(array("code"=>'400','msg'=>'验证码或者手机号码有误'));
    }
    
    
    public function points()
    { 
    	$this->user_id = I('user_id');
    	$p = I('page',0);
    	$type = I('type','all');
    	$this->assign('type',$type);
    	if($type == 'recharge'){
    		$count = M('recharge')->where("user_id=" . $this->user_id)->count();
    		$Page = new Page($count, 16);
    		$Page->firstRow = $p * $Page->listRows;
    		$account_log = M('recharge')->where("user_id=" . $this->user_id)->order('order_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
    	}else if($type == 'points'){
    		$count = M('account_log')->where("user_id=" . $this->user_id ." and pay_points!=0 ")->count();
    		$Page       = new \Think\Page($count,16);
    		$Page->firstRow = $p * $Page->listRows;
    		$account_log = M('account_log')->where("user_id=" . $this->user_id." and pay_points!=0 ")->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
    	}else{
    		$count = M('account_log')->where("user_id=" . $this->user_id)->count();
    		$Page = new Page($count, 16);
    		$Page->firstRow = $p * $Page->listRows;
    		$account_log = M('account_log')->where("user_id=" . $this->user_id)->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
    	}
    	foreach ($account_log as $key=>$value)
    	{
    		$account_log[$key]['change_time'] = date("Y-m-d h:i:s",$value['change_time']);
    	}
    	echo json_encode(array("code"=>'200','msg'=>'成功','res'=>$account_log));
    }
    
    //获取用户中心导航
    public function get_user_nav() {
    	$nav = M('navigation_user')->where(array('is_show'=>1))->order('sort asc')->select();
		if ($nav) {
			foreach($nav as $k=>$v) {
				$nav[$k]['ad_code'] = SITE_URL. $v['ad_code'];
					$nav[$k]['open_type'] ="navigate";
					$nav[$k]['url'] =htmlspecialchars_decode($v['url']);
				
			}
			echo json_encode(array("code"=>'200','msg'=>'获取成功','res'=>$nav));
		} else {
			echo json_encode(array("code"=>'-1','msg'=>'获取失败'));
		}
    }
    //获取关于我们的文章
    public function get_aboutus() {
        $article = M('article')->field('a.*, c.cat_name')->alias('a')
            ->join('ty_article_cat c ON c.cat_id=a.cat_id')
            ->where(array('cat_name'=>'关于我们'))
            ->find();
        $article['content'] = htmlspecialchars_decode($article['content']);
        $article['content'] = str_replace('/Public/upload/', SITE_URL."/Public/upload/", $article['content']);
        exit(json_encode(array('title'=>$article['title'], 'content'=>$article['content'])));
    }

    //获取关于我们的文章
    public function get_article() {
        $name = I('name');
        $article = M('article')->field('a.*')->alias('a')
            ->where(array('title'=>$name,'is_open'=>1))
            ->find();
        $article['content'] = htmlspecialchars_decode($article['content']);
//        $article['content'] = str_replace('/Public/upload/', SITE_URL."/Public/upload/", $article['content']);
        exit(json_encode(array('title'=>$article['title'], 'content'=>$article['content'])));
    }
    //用户充值
    public function user_recharge() {
    	//新增订单
	$data['user_id'] = I('user_id');
	$user = M('users')->where(array('user_id'=>I('user_id')))->find();
	$data['nickname'] = $user['nickname'];
	$data['account'] = floatval(I('account'));
	$data['order_sn'] = 'recharge'.date(ymd).rand(0000, 9999);
	$data['ctime'] = time();
	$data['pay_code'] = 'weixin';
	$data['pay_name'] = '微信支付';
	$order_id = M('recharge')->add($data);
	$open_id = D('users')->where(array("user_id"=>$data['user_id']))->getField("open_id");
	if($order_id){
		$response = $this->getPrePayOrder('用户充值', $data['order_sn'], $data['account'] * 100, $open_id);
        	$x = $this->getOrder($response['prepay_id']);
		$result['wdata'] = $x;
	        $result['pay_money'] = $data['account'];
	        $return_arr = array('status' => 1, 'msg' => '成功', 'result' => $result);
		exit(json_encode($return_arr));
	}else{
		exit(json_encode(array("status"=>'-1','msg'=>'参数错误')));
	}
    }
    
    public function getPrePayOrder($body, $out_trade_no, $total_fee, $open_id)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 
		
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/index.php/WXAPI/Pay/wxCallback';
        $onoce_str = $this->getRandChar(32);
    
        $data["appid"] = $config_value['appid'];
        $data["body"] = $body;
        $data["mch_id"] =$config_value['mchid'];
        $data["nonce_str"] = $onoce_str;
        $data["notify_url"] = $notify_url;
        $data["out_trade_no"] = $out_trade_no;
        $data["spbill_create_ip"] = $this->get_client_ip();
        $data["total_fee"] = $total_fee;
        $data["trade_type"] = "JSAPI";
        $data["openid"] = $open_id;
        $s = $this->getSign($data, false);
        $data["sign"] = $s;
  
        $xml = $this->arrayToXml($data);
        $response = $this->postXmlCurl($xml, $url);
    
        //echo $response;
        // 将微信返回的结果xml转成数组
        return $this->xmlstr_to_array($response);
    }
    
    // 执行第二次签名，才能返回给客户端使用
    public function getOrder($prepayId)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 		
        $data["appId"] = $config_value['appid'];
        $data["nonceStr"] = $this->getRandChar(32);
        $data["package"] = "prepay_id=".$prepayId;
        $data['signType'] = "MD5";
        $data["timeStamp"] = time();
        //$data["partnerid"] = $this->config['mch_id'];
        //$data["prepayid"] = $prepayId;
        
        $s = $this->getSign1($data, false);
        $data["sign"] = $s;
        //$data["prepayid"] = $prepayId;
        return $data;
    }
    
    // 获取指定长度的随机字符串
    function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;
    
        for ($i = 0; $i < $length; $i ++) {
            $str .= $strPol[rand(0, $max)]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
    
        return $str;
    }
    
    /*
     * 获取当前服务器的IP
     */
    function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }
    
    /*
     * 生成签名
     */
    function getSign($Obj)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 				
        foreach ($Obj as $k => $v) {
            $Parameters[strtolower($k)] = $v;
        }
        // 签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        // echo "【string】 =".$String."</br>";
        // 签名步骤二：在string后加入KEY
        $String = $String . "&key=" .  $config_value['key'];
        // echo "<textarea style='width: 50%; height: 150px;'>$String</textarea> <br />";
        // 签名步骤三：MD5加密
        $result_ = strtoupper(md5($String));
        return $result_;
    }
    
    /*
     * 生成签名
     */
    function getSign1($Obj)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']); 		
        foreach ($Obj as $k => $v) {
            $Parameters[strtolower($k)] = $v;
        }
        // 签名步骤一：按字典序排序参数
        ksort($Parameters);
        //$String = $this->formatBizQueryParaMap($Parameters, false);
        $String  = "appId=".$Obj['appId']."&nonceStr=".$Obj['nonceStr']."&package=".$Obj['package']."&signType=MD5&timeStamp=".$Obj['timeStamp']; 
        
        // echo "【string】 =".$String."</br>";
        // 签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $config_value['key'];
        // echo "<textarea style='width: 50%; height: 150px;'>$String</textarea> <br />";
        // 签名步骤三：MD5加密
        //echo $String;
        $result_ = strtoupper(md5($String));
        return $result_;
    }
    
    // 数组转xml
    function arrayToXml($arr)
    {
        
        $xml = "<xml>";
        
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        
        
        return $xml;
    }
    
    /**
     * xml转成数组
     */
    function xmlstr_to_array($xmlstr)
    {
        //$doc = new \DOMDocument();
        //$doc->loadXML($xmlstr);
        //return $this->domnode_to_array($doc->documentElement);
        
        //禁止引用外部xml实体
        
        libxml_disable_entity_loader(true);
        
        $xmlstring = simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA);
        
        $val = json_decode(json_encode($xmlstring),true);
        
        return $val;
        
        
    }
    
    // post https请求，CURLOPT_POSTFIELDS xml格式
    function postXmlCurl($xml, $url, $second = 30)
    {
        // 初始化curl
        $ch = curl_init();
        // 超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        // 这里设置代理，如果有的话
        // curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        // curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        // 运行curl
        $data = curl_exec($ch);
        
        // 返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error" . "<br>";
                echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
                    curl_close($ch);
                    return false;
        }
    }
    
    // 将数组转成uri字符串
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

	//判断远程图片是否存在
	function tianxin_file_exists($url)
	{
		$ch = curl_init();
		curl_setopt($ch, curlopt_url,$url);
		curl_setopt($ch, curlopt_nobody, 1); // 不下载
		curl_setopt($ch, curlopt_failonerror, 1);
		curl_setopt($ch, curlopt_returntransfer, 1);

		if(curl_exec($ch)!==false)
		return true;
		else
		return false;
	}	
    
    function domnode_to_array($node)
    {
        $output = array();
        switch ($node->nodeType) {
            case XML_CDATA_SECTION_NODE:
            case XML_TEXT_NODE:
                $output = trim($node->textContent);
                break;
            case XML_ELEMENT_NODE:
                for ($i = 0, $m = $node->childNodes->length; $i < $m; $i ++) {
                    $child = $node->childNodes->item($i);
                    $v = $this->domnode_to_array($child);
                    if (isset($child->tagName)) {
                        $t = $child->tagName;
                        if (! isset($output[$t])) {
                            $output[$t] = array();
                        }
                        $output[$t][] = $v;
                    } elseif ($v) {
                        $output = (string) $v;
                    }
                }
                if (is_array($output)) {
                    if ($node->attributes->length) {
                        $a = array();
                        foreach ($node->attributes as $attrName => $attrNode) {
                            $a[$attrName] = (string) $attrNode->value;
                        }
                        $output['@attributes'] = $a;
                    }
                    foreach ($output as $t => $v) {
                        if (is_array($v) && count($v) == 1 && $t != '@attributes') {
                            $output[$t] = $v[0];
                        }
                    }
                }
                break;
        }
        return $output;
    }
	
	public function tuijian(){
	    $this->user_id = I('user_id',0);
	    $pages = I("page",0);
		if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));
		
		$count = M('users')->where(array('parent_id'=>$this->user_id))->count();
		$Page = new Page($count,10);
		if ($pages){
		    $Page->firstRow = $Page->listRows * $pages;
		}	
		$show = $Page->show();
	    
	    $data =M('users')->field('user_id,nick_name,company,reg_time,head_pic')->where('parent_id='.$this->user_id)->order('user_id desc')->limit($Page->firstRow,$Page->listRows)->select();
	
	    foreach($data as $key=>$value){
	        $data[$key]['reg_time'] = \date('Y-m-d H:i',$value['reg_time']);
	    }
	    $data['result'] = $arrr;
	    unset($data['show']);
	    exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>$data)));
	}



    public function waitPayOrder()
    {
        $this->user_id = I('user_id',0);
        if(!$this->user_id) exit(json_encode(array('status'=>-1,'msg'=>'缺少参数','result'=>'')));

        $pay_online = tpCache("basic")['is_pays'];
        if($pay_online == 1){
            $user_money = M('users')->where(['user_id'=>$this->user_id])->getField('user_money');
            $open_id = M('users')->where(['user_id'=>$this->user_id])->getField('open_id');
            $pay_master_order_sn = M('order')->where("user_id = {$this->user_id} and pay_status = 0 and order_status < 2 and  (pay_code = 'cod' and driver_id != 0 ) and pay_master_order_sn != '' ")->order('order_id desc')->getField('pay_master_order_sn',true);

            if(!$pay_master_order_sn){
                exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>[])));
            }

            $pay_merge = M('pay_merge_log')->where(['master_order_sn'=>['in',$pay_master_order_sn]])->group('master_order_sn')->order('id asc')->select();

            $data = [];
            $return_price =  0;
            foreach ($pay_merge as $key=>$value){

                $data[$key]['master_order_sn'] = $value['master_order_sn'];
                $data[$key]['add_time'] = $value['add_time'];

                if($value['return_id']){

                    $return_goods = M('return_goods')->field('member_goods_price,goods_num,id,order_id,yijia')->where(['id'=>['in',$value['return_id']]])->select();

                    foreach ($return_goods as $v){
                        $return_price += round($v['member_goods_price'] * $v['goods_num']+$v['yijia'],2);
                        $return_id[] = $v['id'];
                    }
                }



                $order_list = M('order a')
                    ->field('a.coupon_price,c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
                    ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
                    ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
                    ->where(['a.order_id'=>['in',$value['order_sn']],'a.user_id'=>$this->user_id])
                    ->order('a.order_id desc')
                    ->select(); //过滤获取主订单

                //查询产品
                $coupon_price = $waitPayPrice =0;
                foreach ($order_list as $k=>$v){
                    if($v['pay_status'] == 0){
                        $waitPayPrice+= $v['order_amount'];
                        $coupon_price+= $v['coupon_price'];
                    }
                    $order_goods = M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.goods_name,((a.member_goods_price + a.yijia) * a.goods_num) as xiaoji,b.original_img,a.goods_num')->where(['order_id'=>$v['order_id']])->select();
                    foreach ($order_goods as $kk=>$vv){
                        $order_goods[$kk]['xiaoji'] = sanwei($vv['xiaoji']);
                        $order_goods[$kk]['goods_num'] = $vv['goods_num'];
                        $order_goods[$kk]['original_img'] = C('MYOSS')['url'].$vv['original_img'];
                    }
                    $order_list[$k]['goods'] = $order_goods;
                }



                $data[$key]['order_list'] = $order_list;
                $data[$key]['user_money'] = $user_money;
                $data[$key]['waitPayPrice'] = $waitPayPrice;
                if($coupon_price > 0){
                    $data[$key]['waitPayPrice'] = $waitPayPrice.'（已使用'.$coupon_price.'元优惠券）';
                }
                $data[$key]['return_price'] = $return_price;
                $trxamt = sanweis($waitPayPrice-$return_price-$user_money); //减去退货、余额
                $data[$key]['trxamt'] = $trxamt;

                //获取支付信息
                $pay_info = M('pay_merge_log')->where(['master_order_sn'=>$value['master_order_sn'],'result_code'=>'SUCCESS'])->order('id desc')->find();
                if($pay_info && $pay_info['result_code'] == 'SUCCESS'){
                    $data[$key]['pay_info'] = json_decode($pay_info['result'],true);
                }else{
                    $pay = new PayController();
                    $pay_code = $pay->payHFivePay($value['master_order_sn'],$return_id,$user_money,$open_id);
                    $data[$key]['pay_info'] = $pay_code;
                }
                $user_money = $user_money - $waitPayPrice;
                $user_money = $user_money >0 ? $user_money : 0;

            }
            exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$data)));
        }
    }

    public function getMoneyList(){
        $user_id = I('user_id');
        if (!$user_id) {
            exit(json_encode(['code' => -1,'msg' => '用户ID不能为空']));
        }
        $page = I('page', 1); // 当前页码，默认为1
        $pageSize = I('limit', 10); // 每页显示数量，默认为10
        $integral = M('account_log l')
            ->join('ty_users u on u.user_id = l.user_id','left')
            ->field('l.*,u.company')
            ->where(['l.user_id'=>$user_id,'l.order_id'=>0,'l.user_money'=>['neq',0]])
            ->order('log_id desc')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();
        foreach ($integral as $k=>$v){
            $integral[$k]['change_time'] = date('Y-m-d H:i:s',$v['change_time']);
        }
        $this->ajaxReturn([
            'status' => 1,
            'msg' => '获取成功',
            'result' => $integral,
            'page' => $page,
            'pageSize' => $pageSize,
        ]);
    }
}